package com.lookoutthebush.companyindex.services.impl;

import com.lookoutthebush.companyindex.dao.UsersDAO;
import com.lookoutthebush.companyindex.domain.UsersDO;
import com.lookoutthebush.companyindex.enums.UserRoleEnum;
import com.lookoutthebush.companyindex.exception.BizException;
import com.lookoutthebush.companyindex.services.IUsersService;
import com.lookoutthebush.companyindex.util.CheckUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * user
 *
 * @author LookOutTheBush
 * @date 2021/9/18 12:32 下午
 */
@Service
public class UsersServiceImpl implements IUsersService {

    @Resource
    private UsersDAO usersDAO;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public Long createUser(UsersDO usersDO) {
        String field = CheckUtil.isEmpty(usersDO, "username", "password");
        if (!ObjectUtils.isEmpty(field)) {
            throw new BizException(field + "can not be null");
        }
        UsersDO old = usersDAO.queryByUserName(usersDO.getUsername());
        if (null != old) {
            throw new BizException("用户名：" + usersDO.getUsername() + " 已被注册");
        }
        String passwd = usersDO.getPassword();
        String encode = passwordEncoder.encode(passwd);
        usersDO.setPassword(encode);
        return usersDAO.insert(usersDO);
    }

    @Override
    public UsersDO login(String userName, String password) {
        UsersDO usersDO = usersDAO.queryByUserName(userName);
        if (null == usersDO) {
            throw new BizException("请先注册");
        }
        return passwordEncoder.matches(password, usersDO.getPassword()) ? usersDO : null;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(ObjectUtils.isEmpty(username)){
            throw new UsernameNotFoundException("用户名不能为空");
        }
        UsersDO usersDO = usersDAO.queryByUserName(username);
        if (null == usersDO) {
            throw new UsernameNotFoundException("请先注册");
        }
        List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority(UserRoleEnum.getRoleByType(usersDO.getType())));
        return new User(usersDO.getUsername(), usersDO.getPassword(), authorities);
    }
}
